package com.xiaodu.acer.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.chefu.common.net.RestCreator;
import com.chefu.common.util.AppUtils;
import com.chefu.common.util.StringUtils;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.xiaodu.acer.DownloadProgressEvent;
import com.xiaodu.acer.RxUtil;
import com.xiaodu.acer.myapplication.R;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.WeakHashMap;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class UpdateActivity extends RxAppCompatActivity implements View.OnClickListener {

    /***下载地址*/
    public final String FILE_PATH_KEY = "filePath";
    private String file_Path = "http://d.wl.motorsc.com/group2/M00/02/69/Co9PNlq6XBGAJ8TOATEydkPebSA820.apk";


    private android.widget.Button btndownload;
    private android.widget.Button btndel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_update );
        initView();

        setProgress();

    }

    private void setProgress() {
        // 监听下载进度
       RxUtil.getDownloadEventObservable()
                .compose( this.<DownloadProgressEvent>bindToLifecycle() )
                .subscribe( new Action1<DownloadProgressEvent>() {
                    @Override
                    public void call(DownloadProgressEvent downloadProgressEvent) {
                        System.out.println( downloadProgressEvent.getProgress() );
                        System.out.println(downloadProgressEvent.getTotal());
                    }
                } );
    }

    private void initView() {
        this.btndel = (Button) findViewById( R.id.btn_del );
        this.btndownload = (Button) findViewById( R.id.btn_download );

        btndel.setOnClickListener( this );
        btndownload.setOnClickListener( this );
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_download:
                download();
                break;
            case R.id.btn_del:
                deleteAPK();
                break;
        }
    }


    private void download() {
        rxDownloadFileFile();
    }

    private void deleteAPK() {

    }


    /**
     * todo ： 把上面的方法替换了
     */
    private void rxDownloadFileFile() {

        if (StringUtils.isEmpty( file_Path )) {
            Logger.d( "安装包下载失败,请稍后重试" );
            return;
        }

        //file_Path是url
        WeakHashMap<String, Object> params = new WeakHashMap<>();
        RestCreator.
                getRxRestService()
                .download( file_Path, params )
                .map( new Func1<ResponseBody, InputStream>() {
                    @Override
                    public InputStream call(ResponseBody responseBody) {
                        System.out.println( responseBody.byteStream() );
                        return responseBody.byteStream();
                    }
                } )
                .map( new Func1<InputStream, File>() {
                    @Override
                    public File call(InputStream inputStream) {
                        return saveApk( inputStream );
                    }
                } )
                .subscribeOn( Schedulers.io() )
                .observeOn( AndroidSchedulers.mainThread() )
                .subscribe( new Subscriber<File>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                        System.out.println( "开始下载了" );
                    }

                    @Override
                    public void onCompleted() {
                        System.out.println( "下载完成" );
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(File file) {
                        System.out.println( file.getName() );
                        AppUtils.installAPK( file.getName(), UpdateActivity.this );
                    }


                } )
        ;
    }

    /**
     * 保存 apk 文件
     *
     * @param is
     * @return
     */
    File saveApk(InputStream is) {
        File file = getApkFile();
        System.out.println( file.getName() );
        if (writeFile( file, is )) {
            return file;
        } else {
            return null;
        }
    }

    /**
     * 获取 apk 文件夹
     * fixme 可能和之前版本的冲突，可能会导致老用户找不到下载路径
     *
     * @return
     */
    File getApkFileDir() {
        return getApplicationContext().getExternalFilesDir( FILE_PATH_KEY );
    }

    /**
     * 获取 apk 文件
     *
     * @return
     */
    File getApkFile() {
        String appName;
        try {
            appName = getApplicationContext().getPackageManager().getPackageInfo( getApplicationContext().getPackageName(), 0 )
                    .applicationInfo.loadLabel( getApplicationContext().getPackageManager() ).toString();
        } catch (Exception e) {
            // 利用系统api getPackageName()得到的包名，这个异常根本不可能发生
            appName = "";
        }
        return new File( getApkFileDir(), appName + ".apk" );
    }

    /**
     * 根据输入流，保存文件
     *
     * @param file
     * @param is
     * @return
     */
    boolean writeFile(File file, InputStream is) {
        OutputStream os = null;
        try {
            os = new FileOutputStream( file );
            byte data[] = new byte[1024];
            int length = -1;
            while ((length = is.read( data )) != -1) {
                os.write( data, 0, length );
            }
            os.flush();
            return true;
        } catch (Exception e) {
            if (file != null && file.exists()) {
                file.deleteOnExit();
            }
            e.printStackTrace();
        } finally {
            closeStream( os );
            closeStream( is );
        }
        return false;
    }

    /**
     * 关闭流
     *
     * @param closeable
     */
    static void closeStream(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
